<template>
  <!-- 添加商品组件 -->
  <div class="addgoods-container">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图区域 -->
    <el-card>
      <!-- Alert 消息提示框区域 -->
      <el-alert
        title="添加商品信息"
        effect="dark"
        :closable="false"
        type="info"
        center
        show-icon
      >
      </el-alert>

      <!-- Steps 步骤条区域 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- Form 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        label-width="100px"
        ref="addFormRef"
      >
        <!-- Tabs 标签页区域 -->
        <!-- before-leave:切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。 -->
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          class="addTabs"
          :before-leave="beforeTabsLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                clearable
                ref="cascaderRef"
                style="width: 91.6%"
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="parendCateChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyTableData"
              :key="item.attr_id"
              label-width="0px"
            >
              <label style="padding-left:10px;">{{ item.attr_name }}</label>
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(subItem, index) in item.attr_vals"
                  :key="index"
                  :label="subItem"
                  size="mini"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyTableData"
              :key="item.attr_id"
              label-width="0px"
            >
              <label style="padding-left:10px;">{{ item.attr_name }}</label>
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 
                  action:上传的地址
                  headers:设置上传的请求头部
                  on-preview:点击文件列表中已上传的文件时的钩子
                  on-remove:文件列表移除文件时的钩子
                  on-success:文件上传成功时的钩子
                  on-error:文件上传失败时的钩子
                  file-list:上传的文件列表
                  list-type:文件列表的类型
               -->
            <el-upload
              :action="uploadUrl"
              :headers="headersObj"
              :on-preview="handleUploadPreview"
              :on-remove="handleUploadRemove"
              :on-success="handleUploadSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <el-button size="small" type="danger" @click="clearUpload"
                >清空列表</el-button
              >
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器区域 -->
            <quill-editor
              ref="myQuillEditor"
              v-model="addForm.goods_introduce"
              :options="editorOption"
            ></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button
              class="addBtn"
              type="primary"
              size="mini"
              @click="addGoods"
              >完成</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog
      top="5vh"
      class="perviewDialog"
      :visible.sync="previewDialogVisible"
      width="80%"
    >
      <img :src="previewPath" class="perviewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  data() {
    return {
      // 设置要显示的步骤和Tabs标签页
      activeIndex: '0',
      // 添加表单的数据绑定
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [], // 商品分类
        goods_introduce: '', //商品内容
        pics: [], // 图片数组
        attrs: [] // 商品参数
      },
      addFormrules: {
        goods_name: [
          { required: true, message: '请填写商品名称', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请填写商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请填写商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请填写商品重量', trigger: 'blur' }
        ]
      },
      // 分类列表下拉配置对象
      cascaderProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        // 次级菜单的展开方式
        expandTrigger: 'click',
        // 是否严格的遵守父子节点不互相关联(是否可以选择任意一级)
        checkStrictly: false
      },
      // 商品分类列表
      cateList: [],
      // 动态参数数组
      manyTableData: [],
      // 静态参数数组
      onlyTableData: [],
      // 图片上传地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 配置上传图片的请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewDialogVisible: false,
      // 图片预览路径
      previewPath: '',
      // 复文本编辑器配置对象
      editorOption: {}
    }
  },
  created() {
    // 获取商品分类数据
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      // 判断数据获取是否成功
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 级联选择器选择项发生改变时触发函数
    parendCateChange() {
      if (this.addForm.goods_cat.length < 3) {
        this.addForm.goods_cat = []
        this.$message.info('只能选择三级分类')
      }

      // 隐藏级联选择器的下拉选择列表
      this.$refs.cascaderRef.dropDownVisible = false
    },
    // tabs 切换之前调用函数
    beforeTabsLeave(actievName, oldActiveName) {
      var flag = true
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          switch (oldActiveName) {
            case '0':
              if (
                this.addForm.goods_name.trim() === '' ||
                this.addForm.goods_cat.length === 0
              ) {
                flag = false
              }
              break
            default:
              break
          }
        }
      })
      return flag
    },
    // tab 标签页的点击处理函数
    async tabClicked() {
      switch (this.activeIndex) {
        case '1':
          var { data: res } = await this.$http.get(
            `categories/${this.cateId}/attributes`,
            {
              params: { sel: 'many' }
            }
          )

          if (res.meta.status !== 200)
            return this.$message.error('获取动态参数列表失败')

          res.data.forEach(item => {
            item.attr_vals =
              item.attr_vals.trim().length === 0
                ? []
                : item.attr_vals.split(' ')
          })

          this.manyTableData = res.data
          break
        case '2':
          var { data: result } = await this.$http.get(
            `categories/${this.cateId}/attributes`,
            {
              params: { sel: 'only' }
            }
          )

          if (result.meta.status !== 200)
            return this.$message.error('获取静态参数列表失败')

          this.onlyTableData = result.data
          break
        default:
          break
      }
    },
    // 查看图片时处理函数
    handleUploadPreview(file) {
      this.previewDialogVisible = true
      this.previewPath = file.response.data.url
    },
    // 删除图片时处理函数
    handleUploadRemove(file) {
      // 移除表单对象中对应的图片对象
      const index = this.addForm.pics.findIndex(item => item.pic === file.pic)
      this.addForm.pics.splice(index, 1)
    },
    // 上传成功时处理函数
    handleUploadSuccess(response) {
      if (response.meta.status !== 200) return this.$message.error('上传失败！')
      // 把图片路径添加到表单对象中
      var picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
    },
    // 清空上传文件
    async clearUpload() {
      const confirmResult = await this.$confirm(
        '确定要清空文件列表吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果用户确认删除，则返回字符串 confirm
      // 如果用户取消删除，则返回字符串 cancel
      if (confirmResult === 'cancel') return
      this.$refs.uploadRef.clearFiles()
    },
    // 保存商品函数
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项')
        // 使用 lodash 深Copy表单对象
        const form = _.cloneDeep(this.addForm)
        // 处理表单 分类属性
        form.goods_cat = form.goods_cat.join(',')
        // 处理表单的 动态属性
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理表单的 静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        // 把表单的 商品属性数据同步到 form 变量
        form.attrs = this.addForm.attrs
        // 发送添加请求
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加成功!')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 当前选中的三级分类的 id
    cateId() {
      return this.addForm.goods_cat.length > 2
        ? this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
        : null
    }
  },
  watch: {},
  filters: {}
}
</script>

<style lang="less" scoped>
.addgoods-container {
  height: 100%;
  max-height: 100%;
  overflow: auto;

  .el-card {
    height: calc(100% - 60px);
  }

  .el-form-item {
    margin-bottom: 0;
    padding-bottom: 20px;
  }

  .el-checkbox {
    margin: 0 10px 0 0 !important;
  }

  .addBtn {
    margin-top: 10px;
  }
}
</style>

<style lang="less">
/* 全局css */
.perviewDialog {
  .el-dialog {
    .el-dialog__header {
      padding: 0;
    }

    .el-dialog__headerbtn {
      top: 10px;
    }

    .el-dialog__body {
      max-height: 80%;
      overflow: auto;

      .perviewImg {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
